package utils;

import login.*;
import java.nio.file.*;
import java.util.*;

public class FileUtils {
    public static void writeUserToFile(User user, String filename) {
        try {
            Path path = Paths.get(filename);
            if (!Files.exists(path)) Files.createFile(path);
            Files.write(path, (user.toString() + "\n").getBytes(), StandardOpenOption.APPEND);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<User> readUsersFromFile(String filename) {
        List<User> users = new ArrayList<>();
        try {
            Path path = Paths.get(filename);
            if (!Files.exists(path)) return users;
            List<String> lines = Files.readAllLines(path);
            for (String line : lines) {
                String[] parts = line.split(",");
                if (parts.length == 2)
                    users.add(new User(parts[0], parts[1]));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }
}
